package com.fx.controller;

import com.fx.vo.MusicPlayViewItemVo;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.control.Label;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.control.Tooltip;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.text.Font;
import javafx.util.Duration;
import jouvieje.bass.Bass;
import jouvieje.bass.BassInit;
import jouvieje.bass.defines.BASS_SAMPLE;
import jouvieje.bass.defines.BASS_SYNC;
import jouvieje.bass.structures.HSTREAM;
import jouvieje.bass.utils.BufferUtils;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


@Controller
public class MainController {

    public ListView<MusicPlayViewItemVo> musicPlayList;

    public void initialize() {
        BassInit.loadLibraries();
        Bass.BASS_Init(-1, 44100, 0, null, null);

        // 设置自定义单元格工厂以支持长文本滚动
        musicPlayList.setCellFactory(listView -> new ScrollingListCell());

        ObservableList<MusicPlayViewItemVo> items = musicPlayList.getItems();
        String path = "C:\\Users\\Administrator\\Music";
        File file = new File(path);
        List<MusicPlayViewItemVo> strings = listMusicFiles(file);

        items.addAll(strings);


    }
    public void stop() {
        Bass.BASS_Free();
    }

    private int selectedIndex = -1;
    private HSTREAM hstream;


    private void openMusic(String path) {
        if (hstream != null) {
            Bass.BASS_ChannelStop(hstream.asInt());
            hstream.release();
            hstream = null;
        }
        hstream = Bass.BASS_StreamCreateFile(false, BufferUtils.fromStringUTF16(path), 0, 0, BASS_SAMPLE.BASS_SAMPLE_FLOAT | 0x80000000);
        Bass.BASS_ChannelSetSync(hstream.asInt(), BASS_SYNC.BASS_SYNC_END, 0, (hsync, i, i1, pointer) -> {
            if (++selectedIndex >= musicPlayList.getItems().size()) {
                selectedIndex = 0;
            }
            String t = musicPlayList.getItems().get(selectedIndex).getPath();
            openMusic(t);
            Bass.BASS_ChannelPlay(hstream.asInt(),false);

        }, null);
    }
    public void musicPlayListMouseClicked(MouseEvent event) {
        if (event.getClickCount() == 2&&event.getButton().equals(MouseButton.PRIMARY)) {
            selectedIndex = musicPlayList.getSelectionModel().getSelectedIndex();
            String s = musicPlayList.getItems().get(selectedIndex).getPath();
            openMusic(s);
            Bass.BASS_ChannelPlay(hstream.asInt(),false);
        }

    }
    /**
     * 自定义ListView单元格，支持长文本滚动显示
     */
    private static class ScrollingListCell extends ListCell<MusicPlayViewItemVo> {
        private Label label;
        private Timeline scrollTimeline;
        private double textWidth;
        private double cellWidth;
        private boolean isScrolling = false;

        public ScrollingListCell() {
            label = new Label();
            label.setFont(Font.font("Microsoft YaHei", 14));
            label.setPadding(new Insets(0, 5, 0, 5));
            
            // 鼠标进入时开始滚动
            setOnMouseEntered(e -> startScrolling());
            // 鼠标离开时停止滚动
            setOnMouseExited(e -> stopScrolling());
        }

        @Override
        protected void updateItem(MusicPlayViewItemVo item, boolean empty) {
            super.updateItem(item, empty);
            
            if (empty || item == null) {
                setGraphic(null);
                setText(null);
                stopScrolling();
            } else {
                String displayText = item.getName();
                label.setText(displayText);
                
                // 添加Tooltip显示完整文件名
                Tooltip tooltip = new Tooltip(displayText);
                tooltip.setFont(Font.font("Microsoft YaHei", 12));
                setTooltip(tooltip);
                
                setGraphic(label);
                setText(null);
                
                // 计算文本宽度
                textWidth = computeTextWidth(displayText);
                cellWidth = getListView().getWidth() - 40; // 减去padding和滚动条宽度
            }
        }
        
        private double computeTextWidth(String text) {
            javafx.scene.text.Text textNode = new javafx.scene.text.Text(text);
            textNode.setFont(label.getFont());
            return textNode.getBoundsInLocal().getWidth();
        }
        
        private void startScrolling() {
            if (textWidth > cellWidth && !isScrolling) {
                isScrolling = true;
                
                // 创建滚动动画
                scrollTimeline = new Timeline();
                
                // 计算滚动距离
                double scrollDistance = textWidth - cellWidth + 20;
                
                KeyFrame keyFrame1 = new KeyFrame(Duration.ZERO, e -> {
                    label.setTranslateX(0);
                });
                
                KeyFrame keyFrame2 = new KeyFrame(Duration.seconds(2), e -> {
                    label.setTranslateX(-scrollDistance);
                });
                
                KeyFrame keyFrame3 = new KeyFrame(Duration.seconds(4), e -> {
                    label.setTranslateX(0);
                });
                
                scrollTimeline.getKeyFrames().addAll(keyFrame1, keyFrame2, keyFrame3);
                scrollTimeline.setCycleCount(Animation.INDEFINITE);
                scrollTimeline.play();
            }
        }
        
        private void stopScrolling() {
            if (scrollTimeline != null) {
                scrollTimeline.stop();
                label.setTranslateX(0);
            }
            isScrolling = false;
        }
    }

    public static List<MusicPlayViewItemVo> listMusicFiles(File dir) {
        List<MusicPlayViewItemVo> fileList = new ArrayList<>();
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        List<MusicPlayViewItemVo> list = listMusicFiles(file);// 递归处理子目录
                        fileList.addAll(list);
                    } else if (file.isFile() && (file.getName().endsWith(".mp3")||file.getName().endsWith(".wav")||
                            file.getName().endsWith(".flac")||file.getName().endsWith(".m4a"))){
                        MusicPlayViewItemVo musicPlayViewItemVo = new MusicPlayViewItemVo();
                        musicPlayViewItemVo.setName(file.getName());
                        musicPlayViewItemVo.setPath(file.getAbsolutePath());
                        fileList.add(musicPlayViewItemVo);
                    }
                }
            }
        }
        return fileList;
    }

}
